package cn.tedu.csmall.product.repository.impl;

import cn.tedu.csmall.product.pojo.vo.BrandListItemVO;
import cn.tedu.csmall.product.pojo.vo.BrandStandardVO;
import cn.tedu.csmall.product.repository.IBrandCacheRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Repository;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * 处理品牌缓存数据的存储实现类
 *
 * @author java@tedu.cn
 * @version 0.0.1
 */
@Slf4j
@Repository
public class BrandCacheRepositoryImpl implements IBrandCacheRepository {

    @Autowired
    private RedisTemplate<String, Serializable> redisTemplate;

    public static final String KEY_ITEM_PREFIX ="brand:item";
    public static final String KEY_LIST = "brand:list";

    public BrandCacheRepositoryImpl() {
        log.debug("创建处理缓存的对象：BrandCacheRepositoryImpl");
    }

    @Override
    public void save(BrandStandardVO brandStandardVO) {
        ValueOperations<String, Serializable> opsForValue = redisTemplate.opsForValue();
        String key = getItemKey(brandStandardVO.getId());
        opsForValue.set(key, brandStandardVO);
    }

    @Override
    public BrandStandardVO get(Long id) {
        ValueOperations<String, Serializable> opsForValue = redisTemplate.opsForValue();
        String key = getItemKey(id);
        Serializable value = opsForValue.get(key);
        if (value != null) {
            if (value instanceof BrandStandardVO) {
                return (BrandStandardVO) value;
            }
        }
        return null;
    }

    @Override
    public void saveList(List<BrandListItemVO> brandList) {
        ListOperations<String, Serializable> opsForList = redisTemplate.opsForList();
        for (BrandListItemVO brand : brandList) {
            opsForList.rightPush(KEY_LIST, brand);
        }
    }

    @Override
    public List<BrandListItemVO> getList() {
        ListOperations<String, Serializable> opsForList = redisTemplate.opsForList();
        long start = 0L;
        long end = -1L;
        List<Serializable> list = opsForList.range(KEY_LIST, start, end);

        List<BrandListItemVO> brands = new ArrayList<>();
        for (Serializable serializable : list) {
            brands.add((BrandListItemVO) serializable);
        }
        return brands;
    }

    @Override
    public Set<String> getAllKeys() {
        String allKeysPattern = "brand:*";
        return redisTemplate.keys(allKeysPattern);
    }

    @Override
    public Long deleteAll(Set<String> keys) {
        return redisTemplate.delete(keys);
    }

    private String getItemKey(Long id) {
        return KEY_ITEM_PREFIX + id;
    }
}
